# -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals
import os
import sys
import subprocess
import glob

def install_dependencies():
    """安装所需依赖包"""
    print("正在检查并安装所需依赖...")
    required_packages = ["python-docx", "docx2pdf", "pdf2image", "pillow"]
    
    for package in required_packages:
        try:
            __import__(package.replace("-", "_"))
            print("- {} 已安装".format(package))
        except ImportError:
            print("- 正在安装 {}...".format(package))
            try:
                subprocess.check_call([sys.executable, "-m", "pip", "install", package])
                print("  {} 安装成功".format(package))
            except Exception as e:
                print("  无法安装 {}: {}".format(package, e))
                print("  请手动运行: pip install {}".format(package))
                return False
    
    # 检查 pdf2image 依赖 (poppler)
    try:
        from pdf2image import convert_from_path
        test_pdf = os.path.join(os.path.dirname(os.path.abspath(__file__)), "test.pdf")
        with open(test_pdf, "w") as f:
            f.write("%PDF-1.0\n")
        
        try:
            convert_from_path(test_pdf, dpi=72, first_page=1, last_page=1)
            print("- Poppler 已正确配置")
        except Exception as e:
            if "poppler" in str(e).lower():
                print("\n警告: 需要安装 Poppler 才能将 PDF 转换为图像")
                print("Windows: 下载并解压 poppler-xx.xx.x_x86.zip，然后将 bin 目录添加到系统环境变量 PATH 中")
                print("Mac: 使用 brew install poppler")
                print("Linux: 使用 sudo apt-get install poppler-utils")
                return False
        finally:
            if os.path.exists(test_pdf):
                os.remove(test_pdf)
    except Exception as e:
        print("检查 pdf2image 出错: {}".format(e))
        return False
    
    return True

def convert_word_to_images(word_path, output_dir=None):
    """
    将 Word 文档转换为图片集
    :param word_path: Word 文档路径
    :param output_dir: 输出目录，如果不指定，将在 Word 文件同级目录创建同名文件夹
    :return: 输出图片的目录
    """
    from docx2pdf import convert
    from pdf2image import convert_from_path
    import tempfile
    
    # 确定输出目录
    if output_dir is None:
        # 创建与 Word 文件同名的文件夹
        file_name = os.path.basename(word_path)
        file_stem = os.path.splitext(file_name)[0]
        output_dir = os.path.join(os.path.dirname(word_path), file_stem)
    
    # 确保输出目录存在
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
    
    # 创建临时 PDF 文件
    with tempfile.NamedTemporaryFile(suffix='.pdf', delete=False) as temp_pdf:
        temp_pdf_path = temp_pdf.name
    
    try:
        # 转换 Word 到 PDF
        print("正在将 {} 转换为 PDF...".format(os.path.basename(word_path)))
        convert(word_path, temp_pdf_path)
        
        # 转换 PDF 到图片
        print("正在将 PDF 转换为图片...")
        images = convert_from_path(temp_pdf_path, dpi=300)
        
        # 保存图片
        for i, image in enumerate(images):
            image_path = os.path.join(output_dir, "page_{}.png".format(i+1))
            image.save(image_path, "PNG")
            print("已保存: {}".format(image_path))
        
        print("转换完成！图片已保存到: {}".format(output_dir))
        return output_dir
    
    finally:
        # 删除临时 PDF 文件
        if os.path.exists(temp_pdf_path):
            os.remove(temp_pdf_path)

def process_all_word_docs(directory):
    """
    处理指定目录中的所有 Word 文档
    :param directory: 要处理的目录路径
    """
    # 获取所有 Word 文档
    doc_pattern = os.path.join(directory, "*.doc")
    docx_pattern = os.path.join(directory, "*.docx")
    word_files = glob.glob(doc_pattern) + glob.glob(docx_pattern)
    
    if not word_files:
        print("在 {} 中未找到 Word 文档".format(directory))
        return
    
    total = len(word_files)
    print("找到 {} 个 Word 文档".format(total))
    
    for i, word_file in enumerate(word_files, 1):
        try:
            print("\n[{}/{}] 正在处理: {}".format(i, total, os.path.basename(word_file)))
            convert_word_to_images(word_file)
        except Exception as e:
            print("处理 {} 时出错: {}".format(os.path.basename(word_file), e))
    
    print("\n已完成 {} 个 Word 文档的转换".format(total))

def print_help():
    """打印帮助信息"""
    print("\nWord文档转图片工具 (命令行版)")
    print("使用方法:")
    print("  python {} [选项]".format(os.path.basename(sys.argv[0])))
    print("\n选项:")
    print("  --help, -h      显示帮助信息")
    print("  --file=路径      转换指定的Word文档")
    print("  --dir=路径       转换指定目录中的所有Word文档")
    print("  --install       仅安装依赖")
    print("\n示例:")
    print("  python {} --file=文档.docx".format(os.path.basename(sys.argv[0])))
    print("  python {} --dir=文档目录".format(os.path.basename(sys.argv[0])))

def main():
    """主函数"""
    # 如果没有参数，显示帮助信息
    if len(sys.argv) == 1:
        print_help()
        return
    
    # 处理命令行参数
    for arg in sys.argv[1:]:
        if arg in ["--help", "-h"]:
            print_help()
            return
        
        elif arg == "--install":
            install_dependencies()
            return
        
        elif arg.startswith("--file="):
            file_path = arg[7:]
            if not os.path.isfile(file_path):
                print("错误: 文件不存在 - {}".format(file_path))
                return
            
            if install_dependencies():
                try:
                    convert_word_to_images(file_path)
                except Exception as e:
                    print("转换文件时出错: {}".format(e))
            return
        
        elif arg.startswith("--dir="):
            dir_path = arg[6:]
            if not os.path.isdir(dir_path):
                print("错误: 目录不存在 - {}".format(dir_path))
                return
            
            if install_dependencies():
                try:
                    process_all_word_docs(dir_path)
                except Exception as e:
                    print("处理目录时出错: {}".format(e))
            return
        
        else:
            print("错误: 未知参数 - {}".format(arg))
            print_help()
            return

if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print("\n操作已取消")
    except Exception as e:
        print("程序运行出错: {}".format(e)) 